package com.chen.Interceptor;

import com.alibaba.fastjson.JSON;
import com.chen.entity.User;
import com.chen.service.TokenService;
import com.chen.utils.RedisUtil;
import com.chen.utils.UserThreadLocal;
import com.chen.vo.ErrorCode;
import com.chen.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        System.out.println("--------------进入Api拦截器-------------------");
        String AutToken = request.getHeader("Authorization");
        String token = (String) redisUtil.get("TOKEN:" + AutToken);
        if (token == null){
            if(request.getRequestURI().startsWith("/comments/article")){
                Result result = Result.fail(ErrorCode.NO_LOGIN_COMMENTS.getCode(), ErrorCode.NO_LOGIN_COMMENTS.getMsg());
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }else {
                Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "登录失效或者未登录");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }
        }
       User sysUser =tokenService.checkToken(token);
        if (sysUser == null){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
//        获取过期时间redis
        long expire = redisUtil.getExpire("TOKEN:" + AutToken);
//        刷新在线时间
        if (expire> 10){
            redisUtil.set("TOKEN:" + AutToken, AutToken,3600);
        }
//        存到 UserThreadLocal 方便直接取
        UserThreadLocal.put(sysUser);
        //是登录状态，放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        防止内存泄露删除
        UserThreadLocal.remove();
    }
}
